<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Spring AI DeepSeek 演示</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 15px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            overflow: hidden;
        }

        .header {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }

        .header h1 {
            font-size: 2.5em;
            margin-bottom: 10px;
        }

        .header p {
            font-size: 1.2em;
            opacity: 0.9;
        }

        .main-content {
            padding: 30px;
        }

        .api-section {
            padding: 0;
        }

        .api-title {
            font-size: 1.5em;
            color: #333;
            margin-bottom: 15px;
            display: flex;
            align-items: center;
        }

        .api-title::before {
            content: "🚀";
            margin-right: 10px;
            font-size: 1.2em;
        }

        .stream-section {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(102, 126, 234, 0.3);
        }

        .stream-section .api-title {
            color: white;
            font-size: 1.8em;
            margin-bottom: 20px;
        }

        .stream-section .api-title::before {
            content: "🌊";
        }

        .input-group {
            margin-bottom: 20px;
        }

        .input-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #555;
        }

        .stream-section .input-group label {
            color: white;
        }

        .input-group textarea,
        .input-group input {
            width: 100%;
            padding: 12px;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            font-size: 14px;
            transition: border-color 0.3s ease;
        }

        .input-group textarea:focus,
        .input-group input:focus {
            outline: none;
            border-color: #4facfe;
        }

        .input-group textarea {
            min-height: 100px;
            resize: vertical;
        }

        .btn {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: white;
            border: none;
            padding: 12px 25px;
            border-radius: 8px;
            cursor: pointer;
            font-size: 16px;
            font-weight: 600;
            transition: all 0.3s ease;
            margin-right: 10px;
            margin-bottom: 10px;
        }

        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(79, 172, 254, 0.3);
        }

        .btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
        }

        .btn-danger {
            background: linear-gradient(135deg, #ff6b6b 0%, #ee5a52 100%);
        }

        .btn-success {
            background: linear-gradient(135deg, #51cf66 0%, #40c057 100%);
        }

        .response-area {
            margin-top: 20px;
            padding: 20px;
            background: #f8f9fa;
            border-radius: 8px;
            border-left: 4px solid #4facfe;
            min-height: 100px;
            white-space: pre-wrap;
            font-family: 'Courier New', monospace;
            font-size: 14px;
            line-height: 1.5;
        }

        .loading {
            display: none;
            text-align: center;
            padding: 20px;
            color: #666;
        }

        .loading::after {
            content: "";
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid #f3f3f3;
            border-top: 3px solid #4facfe;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin-left: 10px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .stream-output {
            background: #1a202c;
            color: #e2e8f0;
            padding: 25px;
            border-radius: 12px;
            min-height: 300px;
            font-family: 'Courier New', monospace;
            font-size: 15px;
            line-height: 1.8;
            overflow-y: auto;
            max-height: 500px;
            border: 2px solid rgba(255,255,255,0.1);
            position: relative;
        }

        .stream-output::-webkit-scrollbar {
            width: 8px;
        }

        .stream-output::-webkit-scrollbar-track {
            background: #2d3748;
            border-radius: 4px;
        }

        .stream-output::-webkit-scrollbar-thumb {
            background: #4a5568;
            border-radius: 4px;
        }

        .stream-output::-webkit-scrollbar-thumb:hover {
            background: #718096;
        }

        .stream-status {
            position: absolute;
            top: 10px;
            right: 15px;
            padding: 5px 10px;
            background: rgba(0,0,0,0.3);
            border-radius: 15px;
            font-size: 12px;
            color: #a0aec0;
        }

        .stream-status.connecting {
            color: #fbb6ce;
        }

        .stream-status.streaming {
            color: #9ae6b4;
            animation: pulse 2s infinite;
        }

        .stream-status.completed {
            color: #90cdf4;
        }

        .stream-status.error {
            color: #feb2b2;
        }

        @keyframes pulse {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.5; }
        }

        .stream-controls {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
            margin-top: 15px;
        }

        .footer {
            background: #f8f9fa;
            padding: 20px;
            text-align: center;
            color: #666;
            border-top: 1px solid #e0e0e0;
        }

        .tab-container {
            background: white;
            border-radius: 15px;
            overflow: hidden;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }

        .tab-nav {
            display: flex;
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
            border-bottom: 2px solid #e0e0e0;
            overflow-x: auto;
        }

        .tab-btn {
            flex: 1;
            min-width: 150px;
            padding: 15px 20px;
            border: none;
            background: transparent;
            color: #666;
            font-size: 14px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            border-bottom: 3px solid transparent;
            white-space: nowrap;
        }

        .tab-btn:hover {
            background: rgba(79, 172, 254, 0.1);
            color: #4facfe;
        }

        .tab-btn.active {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: white;
            border-bottom-color: #0066cc;
        }

        .tab-content {
            display: none;
            padding: 30px;
            min-height: 500px;
        }

        .tab-content.active {
            display: block;
        }

        .typing-indicator {
            display: inline-block;
            color: #9ae6b4;
        }

        .typing-indicator::after {
            content: '|';
            animation: blink 1s infinite;
        }

        @keyframes blink {
            0%, 50% { opacity: 1; }
            51%, 100% { opacity: 0; }
        }

        .stream-message {
            margin-bottom: 15px;
            padding: 10px 0;
            border-bottom: 1px solid rgba(255,255,255,0.1);
        }

        .stream-message:last-child {
            border-bottom: none;
        }

        .message-timestamp {
            color: #a0aec0;
            font-size: 12px;
            margin-bottom: 5px;
        }

        .message-content {
            color: #e2e8f0;
            line-height: 1.6;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🤖 Spring AI DeepSeek 演示</h1>
            <p>智能文本生成系统 - 营销文案、代码生成、智能问答、聊天对话</p>
        </div>

        <div class="main-content">
            <!-- Tab导航 -->
            <div class="tab-container">
                <div class="tab-nav">
                    <button class="tab-btn active" onclick="switchTab('stream')">🌊 实时流式聊天</button>
                    <button class="tab-btn" onclick="switchTab('marketing')">📝 营销文案生成</button>
                    <button class="tab-btn" onclick="switchTab('code')">💻 代码生成</button>
                    <button class="tab-btn" onclick="switchTab('qa')">❓ 智能问答</button>
                    <button class="tab-btn" onclick="switchTab('chat')">💬 聊天对话</button>
                </div>

                <!-- 实时流式聊天演示 -->
                <div id="stream-tab" class="tab-content active">
                    <div class="stream-section">
                        <div class="api-title">实时流式聊天演示</div>
                        <p style="margin-bottom: 20px; opacity: 0.9;">体验AI实时生成文本的魅力，支持打字机效果和流式响应</p>
                        
                        <div class="input-group">
                            <label for="stream-input">💬 输入您的消息：</label>
                            <textarea id="stream-input" placeholder="例如：讲一个有趣的科幻故事，或者解释一下量子计算的原理" style="background: rgba(255,255,255,0.95); color: #333;"></textarea>
                        </div>
                        
                        <div class="stream-controls">
                            <button class="btn btn-success" onclick="startStream()">🚀 开始流式对话</button>
                            <button class="btn" onclick="pauseStream()" id="pauseBtn" disabled>⏸️ 暂停</button>
                            <button class="btn btn-danger" onclick="stopStream()">⏹️ 停止</button>
                            <button class="btn" onclick="clearStream()">🗑️ 清空</button>
                            <button class="btn" onclick="saveStream()">💾 保存对话</button>
                            <button class="btn" onclick="testStreamEndpoint()" style="background: #ffa726;">🔧 测试端点</button>
                        </div>
                        
                        <div class="stream-output" id="stream-output">
                            <div class="stream-status" id="stream-status">等待开始...</div>
                            <div id="stream-content">
                                <div class="message-content">
                                    🌟 欢迎使用流式聊天演示！
                                    <br><br>
                                    ✨ 特色功能：
                                    <br>• 实时流式响应，逐字显示
                                    <br>• 支持暂停/继续/停止控制
                                    <br>• 自动滚动到最新内容
                                    <br>• 对话历史保存
                                    <br><br>
                                    💡 请在上方输入框中输入您的问题，然后点击"开始流式对话"按钮开始体验！
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 营销文案生成 -->
                <div id="marketing-tab" class="tab-content">
                    <div class="api-section">
                        <div class="api-title">营销文案生成</div>
                        <div class="input-group">
                            <label for="marketing-input">产品描述或需求：</label>
                            <textarea id="marketing-input" placeholder="例如：为智能手表的心率监测功能生成营销文案"></textarea>
                        </div>
                        <div class="input-group">
                            <label for="marketing-temp">创意度 (0.0-2.0)：</label>
                            <input type="number" id="marketing-temp" value="1.2" min="0" max="2" step="0.1">
                        </div>
                        <button class="btn" onclick="generateMarketing()">生成营销文案</button>
                        <div class="loading" id="marketing-loading">生成中...</div>
                        <div class="response-area" id="marketing-response">点击按钮开始生成营销文案...</div>
                    </div>
                </div>

                <!-- 代码生成 -->
                <div id="code-tab" class="tab-content">
                    <div class="api-section">
                        <div class="api-title">代码生成</div>
                        <div class="input-group">
                            <label for="code-input">编程需求：</label>
                            <textarea id="code-input" placeholder="例如：用Java实现一个简单的计算器类"></textarea>
                        </div>
                        <div class="input-group">
                            <label for="code-temp">精确度 (0.0-1.0)：</label>
                            <input type="number" id="code-temp" value="0.1" min="0" max="1" step="0.1">
                        </div>
                        <button class="btn" onclick="generateCode()">生成代码</button>
                        <div class="loading" id="code-loading">生成中...</div>
                        <div class="response-area" id="code-response">点击按钮开始生成代码...</div>
                    </div>
                </div>

                <!-- 智能问答 -->
                <div id="qa-tab" class="tab-content">
                    <div class="api-section">
                        <div class="api-title">智能问答</div>
                        <div class="input-group">
                            <label for="qa-input">您的问题：</label>
                            <textarea id="qa-input" placeholder="例如：什么是Spring Boot的自动配置原理？"></textarea>
                        </div>
                        <button class="btn" onclick="answerQuestion()">获取答案</button>
                        <div class="loading" id="qa-loading">思考中...</div>
                        <div class="response-area" id="qa-response">输入问题获取智能回答...</div>
                    </div>
                </div>

                <!-- 聊天对话 -->
                <div id="chat-tab" class="tab-content">
                    <div class="api-section">
                        <div class="api-title">聊天对话</div>
                        <div class="input-group">
                            <label for="chat-input">聊天消息：</label>
                            <textarea id="chat-input" placeholder="例如：你好，今天天气怎么样？"></textarea>
                        </div>
                        <button class="btn" onclick="chat()">发送消息</button>
                        <div class="loading" id="chat-loading">回复中...</div>
                        <div class="response-area" id="chat-response">开始与AI聊天...</div>
                    </div>
                </div>
            </div>
        </div>

        <div class="footer">
            <p>🚀 Spring AI + DeepSeek 智能文本生成演示 | 版本 1.0.1</p>
            <p>💡 提示：请确保已配置有效的DeepSeek API密钥</p>
        </div>
    </div>

    <script>
        // 全局变量
        let currentEventSource = null;
        let isPaused = false;
        let streamBuffer = '';
        let conversationHistory = [];

        // Tab切换功能
        function switchTab(tabName) {
            // 隐藏所有tab内容
            const allTabs = document.querySelectorAll('.tab-content');
            allTabs.forEach(tab => tab.classList.remove('active'));
            
            // 移除所有tab按钮的active状态
            const allBtns = document.querySelectorAll('.tab-btn');
            allBtns.forEach(btn => btn.classList.remove('active'));
            
            // 显示选中的tab内容
            document.getElementById(tabName + '-tab').classList.add('active');
            
            // 激活对应的tab按钮
            event.target.classList.add('active');
            
            console.log(`切换到 ${tabName} 标签页`);
        }

        // 通用API调用函数
        async function callAPI(endpoint, data, loadingId, responseId) {
            const loading = document.getElementById(loadingId);
            const response = document.getElementById(responseId);
            
            loading.style.display = 'block';
            response.textContent = '处理中...';
            
            try {
                const result = await fetch(endpoint, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(data)
                });
                
                const jsonResponse = await result.json();
                
                if (jsonResponse.success) {
                    response.textContent = jsonResponse.content;
                } else {
                    response.textContent = `错误: ${jsonResponse.errorMessage || '请求失败'}`;
                }
            } catch (error) {
                response.textContent = `网络错误: ${error.message}`;
            } finally {
                loading.style.display = 'none';
            }
        }

        // 营销文案生成
        function generateMarketing() {
            const content = document.getElementById('marketing-input').value;
            const temperature = parseFloat(document.getElementById('marketing-temp').value);
            
            if (!content.trim()) {
                alert('请输入产品描述或需求');
                return;
            }
            
            callAPI('/api/ai/marketing', {
                content: content,
                temperature: temperature,
                maxTokens: 800
            }, 'marketing-loading', 'marketing-response');
        }

        // 代码生成
        function generateCode() {
            const content = document.getElementById('code-input').value;
            const temperature = parseFloat(document.getElementById('code-temp').value);
            
            if (!content.trim()) {
                alert('请输入编程需求');
                return;
            }
            
            callAPI('/api/ai/code', {
                content: content,
                temperature: temperature,
                maxTokens: 1500
            }, 'code-loading', 'code-response');
        }

        // 智能问答
        function answerQuestion() {
            const content = document.getElementById('qa-input').value;
            
            if (!content.trim()) {
                alert('请输入您的问题');
                return;
            }
            
            callAPI('/api/ai/qa', {
                content: content,
                temperature: 0.7,
                maxTokens: 1000
            }, 'qa-loading', 'qa-response');
        }

        // 聊天对话
        function chat() {
            const content = document.getElementById('chat-input').value;
            
            if (!content.trim()) {
                alert('请输入聊天消息');
                return;
            }
            
            callAPI('/api/ai/chat', {
                content: content,
                temperature: 0.9,
                maxTokens: 800
            }, 'chat-loading', 'chat-response');
        }

        // 更新流式状态
        function updateStreamStatus(status, message) {
            const statusElement = document.getElementById('stream-status');
            statusElement.className = `stream-status ${status}`;
            statusElement.textContent = message;
        }

        // 添加消息到流式输出
        function addStreamMessage(content, isUser = false) {
            const streamContent = document.getElementById('stream-content');
            const timestamp = new Date().toLocaleTimeString();
            
            const messageDiv = document.createElement('div');
            messageDiv.className = 'stream-message';
            messageDiv.innerHTML = `
                <div class="message-timestamp">${timestamp} ${isUser ? '👤 您' : '🤖 AI'}</div>
                <div class="message-content">${content}</div>
            `;
            
            streamContent.appendChild(messageDiv);
            
            // 滚动到底部
            const output = document.getElementById('stream-output');
            output.scrollTop = output.scrollHeight;
        }

        // 流式聊天
        function startStream() {
            const message = document.getElementById('stream-input').value;
            
            if (!message.trim()) {
                alert('请输入流式消息');
                return;
            }
            
            // 停止之前的连接
            if (currentEventSource) {
                currentEventSource.close();
            }
            
            // 添加用户消息
            addStreamMessage(message, true);
            
            // 清空输入框
            document.getElementById('stream-input').value = '';
            
            // 重置状态
            isPaused = false;
            streamBuffer = '';
            
            // 更新状态和按钮
            updateStreamStatus('connecting', '连接中...');
            document.querySelector('button[onclick="startStream()"]').disabled = true;
            document.getElementById('pauseBtn').disabled = false;
            
            // 创建新的EventSource连接
            const encodedMessage = encodeURIComponent(message);
            const streamUrl = `/api/stream/chat-fixed?message=${encodedMessage}`;
            console.log('连接流式端点:', streamUrl);
            
            currentEventSource = new EventSource(streamUrl);
            
            // 添加AI响应容器
            const aiMessageDiv = document.createElement('div');
            aiMessageDiv.className = 'stream-message';
            aiMessageDiv.innerHTML = `
                <div class="message-timestamp">${new Date().toLocaleTimeString()} 🤖 AI</div>
                <div class="message-content"><span class="typing-indicator"></span></div>
            `;
            document.getElementById('stream-content').appendChild(aiMessageDiv);
            const aiContentDiv = aiMessageDiv.querySelector('.message-content');
            
            currentEventSource.onopen = function() {
                console.log('SSE连接已建立');
                updateStreamStatus('streaming', '正在接收...');
            };
            
            currentEventSource.onmessage = function(event) {
                if (isPaused) return;
                
                console.log('收到SSE数据:', event.data);
                
                // 检查是否是完成信号
                if (event.data === '[DONE]') {
                    console.log('流式响应完成');
                    updateStreamStatus('completed', '完成');
                    
                    // 移除打字指示器
                    const typingIndicator = aiContentDiv.querySelector('.typing-indicator');
                    if (typingIndicator) {
                        typingIndicator.remove();
                    }
                    
                    // 保存到历史记录
                    conversationHistory.push({
                        user: message,
                        ai: streamBuffer,
                        timestamp: new Date().toISOString()
                    });
                    
                    // 清理连接
                    currentEventSource.close();
                    currentEventSource = null;
                    document.querySelector('button[onclick="startStream()"]').disabled = false;
                    document.getElementById('pauseBtn').disabled = true;
                    return;
                }
                
                // 检查是否是错误信号
                if (event.data.startsWith('[ERROR]')) {
                    console.log('流式响应错误:', event.data);
                    updateStreamStatus('error', '错误');
                    const errorMsg = event.data.replace('[ERROR]', '').trim();
                    aiContentDiv.innerHTML = `❌ ${errorMsg || '流式响应出现错误'}`;
                    
                    // 清理连接
                    currentEventSource.close();
                    currentEventSource = null;
                    document.querySelector('button[onclick="startStream()"]').disabled = false;
                    document.getElementById('pauseBtn').disabled = true;
                    return;
                }
                
                // 处理正常的流式数据
                if (event.data && event.data.trim() !== '') {
                    console.log('处理流式数据块:', event.data);
                    
                    // 累积响应内容
                    streamBuffer += event.data;
                    
                    // 移除打字指示器并更新内容
                    const typingIndicator = aiContentDiv.querySelector('.typing-indicator');
                    if (typingIndicator) {
                        typingIndicator.remove();
                    }
                    
                    // 转义HTML内容并保持换行
                    const escapedContent = streamBuffer
                        .replace(/&/g, '&amp;')
                        .replace(/</g, '&lt;')
                        .replace(/>/g, '&gt;')
                        .replace(/"/g, '&quot;')
                        .replace(/'/g, '&#39;')
                        .replace(/\n/g, '<br>');
                    
                    aiContentDiv.innerHTML = escapedContent + '<span class="typing-indicator"></span>';
                    
                    // 滚动到底部
                    const output = document.getElementById('stream-output');
                    output.scrollTop = output.scrollHeight;
                }
            };
            
            currentEventSource.onerror = function(event) {
                console.error('SSE连接错误:', event);
                
                // 如果连接已经被正常关闭，不处理错误
                if (!currentEventSource) {
                    console.log('连接已正常关闭，忽略错误事件');
                    return;
                }
                
                console.log('连接状态:', currentEventSource.readyState);
                updateStreamStatus('error', '连接错误');
                
                // 检查连接状态
                if (currentEventSource.readyState === EventSource.CONNECTING) {
                    aiContentDiv.innerHTML = '❌ 正在重新连接...';
                } else if (currentEventSource.readyState === EventSource.CLOSED) {
                    aiContentDiv.innerHTML = '❌ 连接已关闭，请检查网络或API配置';
                } else {
                    aiContentDiv.innerHTML = '❌ 连接错误，请检查服务器状态';
                }
                
                // 清理连接
                if (currentEventSource) {
                    currentEventSource.close();
                    currentEventSource = null;
                }
                
                // 重置按钮状态
                document.querySelector('button[onclick="startStream()"]').disabled = false;
                document.getElementById('pauseBtn').disabled = true;
            };
        }

        // 暂停/继续流式响应
        function pauseStream() {
            const pauseBtn = document.getElementById('pauseBtn');
            if (isPaused) {
                isPaused = false;
                pauseBtn.textContent = '⏸️ 暂停';
                updateStreamStatus('streaming', '继续接收...');
            } else {
                isPaused = true;
                pauseBtn.textContent = '▶️ 继续';
                updateStreamStatus('paused', '已暂停');
            }
        }

        // 停止流式响应
        function stopStream() {
            if (currentEventSource) {
                currentEventSource.close();
                currentEventSource = null;
            }
            updateStreamStatus('completed', '已停止');
            document.querySelector('button[onclick="startStream()"]').disabled = false;
            document.getElementById('pauseBtn').disabled = true;
            isPaused = false;
            document.getElementById('pauseBtn').textContent = '⏸️ 暂停';
        }

        // 清空流式输出
        function clearStream() {
            document.getElementById('stream-content').innerHTML = `
                <div class="message-content">
                    🌟 欢迎使用流式聊天演示！
                    <br><br>
                    ✨ 特色功能：
                    <br>• 实时流式响应，逐字显示
                    <br>• 支持暂停/继续/停止控制
                    <br>• 自动滚动到最新内容
                    <br>• 对话历史保存
                    <br><br>
                    💡 请在上方输入框中输入您的问题，然后点击"开始流式对话"按钮开始体验！
                </div>
            `;
            updateStreamStatus('ready', '等待开始...');
            streamBuffer = '';
        }

        // 保存对话历史
        function saveStream() {
            if (conversationHistory.length === 0) {
                alert('暂无对话历史可保存');
                return;
            }
            
            const content = conversationHistory.map(item => 
                `时间: ${new Date(item.timestamp).toLocaleString()}\n用户: ${item.user}\nAI: ${item.ai}\n${'='.repeat(50)}\n`
            ).join('\n');
            
            const blob = new Blob([content], { type: 'text/plain;charset=utf-8' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `AI对话历史_${new Date().toISOString().slice(0,10)}.txt`;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
            
            alert('对话历史已保存到文件');
        }

        // 测试流式端点
        async function testStreamEndpoint() {
            updateStreamStatus('connecting', '测试中...');
            
            try {
                // 测试基础健康检查
                console.log('测试基础健康检查...');
                const healthResponse = await fetch('/api/ai/health');
                const healthText = await healthResponse.text();
                console.log('健康检查结果:', healthText);
                
                // 测试流式信息端点
                console.log('测试流式信息端点...');
                const infoResponse = await fetch('/api/stream/info');
                const infoData = await infoResponse.json();
                console.log('流式信息:', infoData);
                
                // 测试流式健康检查
                console.log('测试流式健康检查...');
                const streamHealthResponse = await fetch('/api/stream/health');
                const streamHealthText = await streamHealthResponse.text();
                console.log('流式健康检查结果:', streamHealthText);
                
                // 显示测试结果
                const output = document.getElementById('stream-content');
                output.innerHTML = `
                    <div class="message-content">
                        🔧 端点测试结果：
                        <br><br>
                        ✅ 基础健康检查: ${healthText}
                        <br><br>
                        ✅ 流式信息端点: 正常
                        <br>• 描述: ${infoData.description}
                        <br>• 可用端点: ${infoData.endpoints.length} 个
                        <br><br>
                        ✅ 流式健康检查: 正常
                        <br>• 响应长度: ${streamHealthText.length} 字符
                        <br><br>
                        💡 所有端点测试通过，流式聊天应该可以正常工作！
                    </div>
                `;
                
                updateStreamStatus('completed', '测试完成');
                
            } catch (error) {
                console.error('端点测试失败:', error);
                
                const output = document.getElementById('stream-content');
                output.innerHTML = `
                    <div class="message-content">
                        ❌ 端点测试失败：
                        <br><br>
                        错误信息: ${error.message}
                        <br><br>
                        💡 可能的原因：
                        <br>• 应用未完全启动
                        <br>• API密钥未正确配置
                        <br>• 网络连接问题
                        <br>• 服务器内部错误
                        <br><br>
                        🔧 建议解决方案：
                        <br>1. 检查控制台日志
                        <br>2. 运行 test-stream-endpoint.bat
                        <br>3. 确认API密钥配置
                        <br>4. 重启应用
                    </div>
                `;
                
                updateStreamStatus('error', '测试失败');
            }
        }

        // 页面加载完成后的初始化
        document.addEventListener('DOMContentLoaded', function() {
            console.log('🚀 Spring AI DeepSeek 演示页面加载完成');
            
            // 检查服务状态
            fetch('/api/ai/health')
                .then(response => response.text())
                .then(data => {
                    console.log('✅ 服务状态:', data);
                    updateStreamStatus('ready', '服务就绪');
                })
                .catch(error => {
                    console.warn('⚠️ 服务检查失败:', error);
                    updateStreamStatus('error', '服务异常');
                });
            
            // 添加键盘快捷键
            document.getElementById('stream-input').addEventListener('keydown', function(e) {
                if (e.ctrlKey && e.key === 'Enter') {
                    startStream();
                }
            });
        });
    </script>
</body>
</html> 